package com.yuanthink.gwt.client.workplace;

import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.yuanthink.gwt.client.IController;
import com.yuanthink.gwt.client.actions.IAction;
import com.yuanthink.gwt.client.eventbus.EventBus;
import com.yuanthink.gwt.client.eventbus.IAppEventHandler;
import com.yuanthink.gwt.client.registry.ActionRegistry;
import com.yuanthink.gwt.client.registry.IActionRegistry;

@SuppressWarnings("rawtypes")
public class WorkspaceController implements ValueChangeHandler, IController, IAppEventHandler {

	EventBus eventBus;
	LayoutContainer container;
	WorkspacePresenter presenter;
	ModelData config;
	
	public WorkspaceController(EventBus eventBus) {
        this.eventBus = eventBus;
        config = new BaseModelData();
        config.set("name", "远思技术");
    }
	
	@Override
	public boolean onEvent(String eventName, ModelData eventData) {
		if (eventName.equals("action")) {
			config = eventData;
			String actionId = eventData.get("actionId");
			IAction action = ActionRegistry.getInstance().getAction(actionId);
			action.execute(eventData);
			return true;
		}
		return false;
	}

	@Override
	public void setEventBus(EventBus eventBus) {
		this.eventBus = eventBus;
	}

	@Override
	public EventBus getEventBus() {
		return eventBus;
	}

	@Override
	public void bind() {
		eventBus.addHandler("action", this);
		IActionRegistry actionRegistry = ActionRegistry.getInstance();
        actionRegistry.register("default", new DefaultAction(eventBus));
	}

	@Override
	public void go(LayoutContainer container) {
		bind();
        this.container = container;
        
        presenter = new WorkspacePresenter(eventBus);
        presenter.go(container);
        presenter.setCurrentWorkplace(config);
	}
	
	public void onValueChange(ValueChangeEvent event) {
		presenter.setCurrentWorkplace(config);
	}
}
